package com.wenjiang.util;


import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Component
@Slf4j
public class EmailUtils {
    @Value("${spring.mail.username}")
    String from;

    @Autowired
    JavaMailSender javaMailSender;

    //发送邮件的模板引擎
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    char [] codeSequence={'A','B','C','D','E','F','G','H','I','J',
            'K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
            '1','2','3','4','5','6','7','8','9'};


    public void SendEmail(Object params ,String title,String templateName,String email){
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(InternetAddress.parse(email));//发送给谁
            mimeMessageHelper.setSubject("【" + title + "-" + LocalDate.now() + " " + LocalTime.now().withNano(0) + "】");//邮件标题
            //放入参数
            Map<String, Object> model = new HashMap<>();
            model.put("params", params);
            Template template = freeMarkerConfigurer.getConfiguration().getTemplate(templateName);
            //解析模板
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            mimeMessageHelper.setText(text, true);
            javaMailSender.send(mimeMessage);
        }catch (Exception e){
            log.error(e.getMessage());
        }
    }


    public String genercode(){


        StringBuilder stringBuilder =new StringBuilder();

        Random random= new Random();


        for(int i=1;i<=4;i++){
            //生成随机数
            char c= codeSequence[random.nextInt(codeSequence.length)];
            //拼接验证码
            stringBuilder.append(c);
        }

        return  stringBuilder.toString();

    }


}
